# -*- coding: utf-8 -*-

from odoo import models, fields, api, _
import logging
from xml.dom.minidom import parse
from odoo.exceptions import UserError
import time
import xml.dom.minidom
_logger = logging.getLogger(__name__)

class purchase_report(models.Model):
    _inherit = "purchase.order"

    contact = fields.Many2one('res.partner',string=u'供应商联系人')
    child_ids = fields.One2many(related='partner_id.child_ids')

    @api.multi
    def print_inherit_purchase_report(self):
        return self.env['report'].get_action(self,'lontry_add.inherit_purchase_report')

class lontry_orderline(models.Model):
    _inherit = "sale.order.line"

    delivery_date = fields.Date(u'到货日期')
    lonytry_sale_client_id = fields.Char(string='订单号')

class lonytry_sale(models.Model):
    _inherit = 'sale.order'

    lonytry_sale_project_id = fields.Char(string='项目编号')
    # lonytry_sale_client_id = fields.Char(string='订单号')
    contact = fields.Many2one('res.partner',u'商务对接人',help="与该订单对接的联系人")
    child_ids = fields.One2many(related='partner_id.child_ids')

    stock_picking_id = fields.Many2one('stock.picking')

    # @api.one
    # @api.depends('contact','partner_invoice_id','partner_shipping_id')
    # def depends_partner_info(self):
    #     _logger.info("00000000000000000")
    #     if self.contact:
    #         if self.contact.parent_id:
    #             pass
    #         else:
    #             self.contact.partner_id = self.partner_id.id
    #     if self.partner_invoice_id:
    #         if self.partner_invoice_id.parent_id:
    #             pass
    #         else:
    #             self.partner_invoice_id.partner_id = self.partner_id.id
    #     if self.partner_shipping_id:
    #         if self.partner_shipping_id.parent_id:
    #             pass
    #         else:
    #             self.partner_shipping_id.partner_id = self.partner_id.id

    @api.multi
    def action_confirm(self):
        return super(lonytry_sale, self).action_confirm()

    @api.multi
    def print_inherit_sale_report(self):
        return self.env['report'].get_action(self,'lontry_add.inherit_sale_report')

    delivery_way = fields.Many2one('delivery.way',u'交货方式')
    transport_cost = fields.Selection([('a',u'供方'),('b',u'需方')],u'运输费用')
    warranty = fields.Many2one('warranty.way',u'产品保修')
    
    ttax = fields.Many2one('t.tax',u'税率及发票')
    

    @api.multi
    def update_stock_pick(self):
        if(self.stock_picking_id):
            self.stock_picking_id.update_sale_order_info()

    # @api.multi
    # @api.one
    def get_client_info(self):
        # ('template','=',self.product_id.product_tmpl_id.id)]
    #     self.pro_code = rec.pro_code
    #     self.pro_name = rec.pro_name
        # for line in self.order_line :
        #     rec = self.env['pro.material'].sudo().search([('pro','=',self.partner_id.id),('template','=',line.product_id.product_tmpl_id.id)])
        #     _logger.info(rec)
        #     if(len(rec)>0):
        #         line.pro_code = rec[0].pro_code
        #         line.pro_name = rec[0].pro_name
        # _logger.info(self.order_line.ids)
        # _logger.info(self.order_line)
        # _logger.info(self.mapped('order_line'))
        for rec in self.order_line:
            rec_ids = rec.product_id.material
            for reg in rec_ids:
                if str(self.partner_id.id) == str(reg.pro.id):
                    _logger.info("22")
                    rec.pro_name = reg.pro_name
                    rec.pro_code = reg.pro_code
            

    @api.multi
    @api.onchange('partner_id')
    def _find_line_sale_order_pro(self):
        if self.partner_id:
            for rec in self.order_line:
                rec_ids = rec.product_id.material
                for reg in rec_ids:
                    if str(self.partner_id.id) == str(reg.pro.id):
                        rec.pro_name = reg.pro_name
                        rec.pro_code = reg.pro_code


class sto_move(models.Model):
    _inherit = 'stock.move'
    # _inherit = 'stock.pack.operation'

    pro_code = fields.Char(u'客户物料编码')
    pro_name = fields.Char(u'客户物料名称')
    comment = fields.Char(u'备注')
    lname = fields.Char(u'规格')
    lonytry_sale_client_id = fields.Char(string='订单号')

    # @api.model
    # def create(self, vals):
    #     _logger.info(vals)
    #     if(vals.has_key('origin')):

    #         sale_order = self.env['sale.order'].sudo().search([('name', '=', vals['origin'])])
    #         # sale_order = self.picking_id.sale_order_id
    #         line = sale_order.order_line
    #         for l in line:
    #             if l.product_id.id == vals['product_id']:
    #                 vals['pro_code'] = l.pro_code
    #                 vals['pro_name'] = l.pro_name
    #                 vals['comment'] = l.comment
    #                 vals['lname'] = l.name
    #     return super(sto_move, self).create(vals)

class stock_report(models.Model):
    _inherit = "stock.picking"

    lonytry_sale_project_id = fields.Char(string='项目编号')
    # lonytry_sale_client_id = fields.Char(string='订单号')
    
    contact = fields.Many2one('res.partner',u'申请人',help="调拨单据的发起者")
    sale_order_id = fields.Many2one('sale.order')
    purchase_order_id = fields.Many2one('purchase.order')

    @api.multi
    @api.returns('self', lambda value: value.id)
    def message_post(self, body='', subject=None, message_type='notification',
                     subtype=None, parent_id=False, attachments=None,
                     content_subtype='html', **kwargs):
        page_settings = self.env['ir.values'].get_default('sale.config.settings', 'page_settings')
        # _logger.info(body)
        if('data-oe-model="sale.order"' in body):
            DOMTree = xml.dom.minidom.parseString(body)
            collection = DOMTree.documentElement
            a = collection.getElementsByTagName("a")
            sale_order_id = a[0].getAttribute("data-oe-id")
            self.write({'sale_order_id':int(sale_order_id)})
            self.sale_order_id.write({'stock_picking_id':self.id})
            self.update_sale_order_info()

        if('data-oe-model="purchase.order"' in body):
            DOMTree = xml.dom.minidom.parseString(body)
            collection = DOMTree.documentElement
            a = collection.getElementsByTagName("a")
            purchase_order_id = a[0].getAttribute("data-oe-id")
            self.write({'purchase_order_id':int(purchase_order_id)})
            # self.sale_order_id.write({'stock_picking_id':self.id})s
            self.update_purchase_order_info()

        if page_settings:
            body = body.replace("data-oe-id=", "einfo-no=")
        return super(stock_report,self).message_post(body,subject,message_type,subtype,parent_id,attachments,content_subtype,**kwargs)

    @api.multi
    def print_inherit_stock_report(self):
        return self.env['report'].get_action(self,'lontry_add.inherit_stock_report')

    def update_sale_order_info(self):
        self.contact = self.sale_order_id.contact
        self.lonytry_sale_project_id = self.sale_order_id.lonytry_sale_project_id
        # self.lonytry_sale_client_id = self.sale_order_id.lonytry_sale_client_id
        # _logger.info(self.move_lines)
        for move_line in self.move_lines:
            # _logger.info(move_line.name)
            # _logger.info(move_line.product_id)
            for l in self.sale_order_id.order_line:
                # _logger.info(l.product_id.id)
                if l.product_id.id == move_line.product_id.id:
                    # _logger.info(l.pro_code)
                    move_line.pro_code = l.pro_code
                    move_line.pro_name = l.pro_name
                    move_line.comment = l.comment
                    move_line.lname = l.name
                    move_line.lonytry_sale_client_id = l.lonytry_sale_client_id
        return 


    def update_purchase_order_info(self):
        # self.lonytry_sale_client_id = self.purchase_order_id.partner_ref
        return 

class pro_template(models.Model):
    _inherit = "product.template"

    material = fields.One2many('pro.material','template',u'客户物料信息')

class pro_material(models.Model):
    _name = 'pro.material'

    pro_code = fields.Char(u'客户物料编码')
    pro_name = fields.Char(u'客户物料名称')
    pro = fields.Many2one('res.partner',u'客户')
    template = fields.Many2one('product.template')

class sale_line(models.Model):
    _inherit = "sale.order.line"

    pro_code = fields.Char(u'客户物料编码',)
    pro_name = fields.Char(u'客户物料名称',)
    comment = fields.Char(u'备注')
    tax_total = fields.Monetary(u'含税总价',compute='com_tax')

    @api.onchange('pro_code','pro_name')
    def onchange_code_name(self):
        if self.pro_code and self.pro_name and self.product_id:
            # self.product_id.product_tmpl_id
            material = self.env['pro.material'].search([('template','=',self.product_id.product_tmpl_id.id),('pro','=',self.order_id.partner_id.id)])
            if material:
            
                material.write({'pro_code':self.pro_code,'pro_name':self.pro_name})
            else:
                self.env['pro.material'].create({
                    'template':self.product_id.product_tmpl_id.id,
                    'pro':self.order_id.partner_id.id,
                    'pro_code':self.pro_code,
                    'pro_name':self.pro_name
                })

    @api.depends('price_unit','product_uom_qty')
    @api.one
    def com_tax(self):
        price_unit = self.price_unit
        product_uom_qty = self.product_uom_qty
        self.tax_total = price_unit * product_uom_qty

    # @api.one
    @api.onchange('order_partner_id','product_id')
    def _find_line_sale_order(self):
        if self.order_partner_id:
            maters = self.product_id.material
            for rec in maters:
                if str(self.order_partner_id.id) == str(rec.pro.id):
                    self.pro_name = rec.pro_name
                    self.pro_code = rec.pro_code

        #     self.pro_code = 
        # if self.partner_id:
        #     for rec in self.order_line:
        #         _logger.info(rec.order_partner_id.name)
        #         rec_ids = rec.product_id.material
        #         for reg in rec_ids:
        #             if str(self.partner_id.id) == str(reg.pro.id):
        #                 _logger.info("22")
        #                 _logger.info(reg.pro_name)
        #                 _logger.info(rec.product_id.name)
        #                 # _logger.info(reg.pro_name)
        #                 # _logger.info("22")
        #                 rec.pro_name = reg.pro_name
        #                 rec.pro_code = reg.pro_code
        #                 _logger.info(rec.pro_name)


class pur_order(models.Model):
    _inherit = 'purchase.order'

    delivery_way = fields.Many2one('delivery.way',u'交货方式')
    transport_cost = fields.Selection([('a',u'供方'),('b',u'需方')],u'运输费用')
    warranty = fields.Many2one('warranty.way',u'产品保修')
    ttax = fields.Many2one('t.tax',u'税率及发票')
    buyer = fields.Many2one('res.users',u'采购员')

class delivery_way(models.Model):
    _name = 'delivery.way'

    name = fields.Char(u'交货方式')

class warranty_way(models.Model):
    _name = 'warranty.way'

    name = fields.Char(u'产品保修')

class t_tax(models.Model):
    _name = 't.tax'

    name = fields.Char(u'税率及发票')

class lontry_account(models.Model):
    _inherit = "account.invoice.line"

    lonytry_sale_client_id = fields.Char(string='订单号')

class PickingType(models.Model):
    _inherit = "stock.picking.type"

    user_ids = fields.Many2many("res.users",string=u'使用者')

class SalePayment(models.TransientModel):
    _inherit = "sale.advance.payment.inv"


    @api.multi
    def create_invoices(self):
        sale_orders = self.env['sale.order'].browse(self._context.get('active_ids', []))

        if self.advance_payment_method == 'delivered':
            sale_orders.action_invoice_create()
        elif self.advance_payment_method == 'all':
            sale_orders.action_invoice_create(final=True)
        else:
            # Create deposit product if necessary
            if not self.product_id:
                vals = self._prepare_deposit_product()
                self.product_id = self.env['product.product'].create(vals)
                self.env['ir.values'].sudo().set_default('sale.config.settings', 'deposit_product_id_setting', self.product_id.id)

            sale_line_obj = self.env['sale.order.line']
            for order in sale_orders:
                if self.advance_payment_method == 'percentage':
                    amount = order.amount_untaxed * self.amount / 100
                else:
                    amount = self.amount
                if self.product_id.invoice_policy != 'order':
                    raise UserError(_('The product used to invoice a down payment should have an invoice policy set to "Ordered quantities". Please update your deposit product to be able to create a deposit invoice.'))
                if self.product_id.type != 'service':
                    raise UserError(_("The product used to invoice a down payment should be of type 'Service'. Please use another product or update this product."))
                if order.fiscal_position_id and self.product_id.taxes_id:
                    tax_ids = order.fiscal_position_id.map_tax(self.product_id.taxes_id).ids
                else:
                    tax_ids = self.product_id.taxes_id.ids
                so_line = sale_line_obj.create({
                    'name': _('Advance: %s') % (time.strftime('%m %Y'),),
                    'price_unit': amount,
                    'product_uom_qty': 0.0,
                    'order_id': order.id,
                    'discount': 0.0,
                    'product_uom': self.product_id.uom_id.id,
                    'product_id': self.product_id.id,
                    'tax_id': [(6, 0, tax_ids)],
                })
                self._create_invoice(order, so_line, amount)
        _logger.info("teteteteteteetetSS")
        _logger.info(sale_orders.invoice_ids)
        invoiceids = sale_orders.invoice_ids
        for i in invoiceids:
            for line in i.invoice_line_ids:
                for s in sale_orders.order_line:
                    if s.product_id == line.product_id:
                        line.lonytry_sale_client_id = s.lonytry_sale_client_id

        if self._context.get('open_invoices', False):
            return sale_orders.action_view_invoice()
        return {'type': 'ir.actions.act_window_close'}